package com.dmall.trade.factory;

import com.dmall.trade.exception.TradeException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xiao1.wang
 * @date 2021-06-05 11:27
 */
public class BeanFactory {

    public static final ConcurrentHashMap<Class<?>, Object> BEAN_FACTORY = new ConcurrentHashMap<Class<?>, Object>();

    public static final <T> T getBean(Class<T> clazz) {
        return (T) BEAN_FACTORY.get(clazz);
    }

    public static final <T> void addBean(Class<T> clazz, Object bean) {
        if (clazz == null || bean == null) {
            return;
        }
        Class<?> beanClass = bean.getClass();
        if (beanClass != clazz) {
            throw new TradeException();
        }

        synchronized (BeanFactory.class) {
            if (BEAN_FACTORY.containsKey(clazz)) {
                return;
            }
            BEAN_FACTORY.put(clazz, bean);
        }
    }
}
